package com.beiding.natago2.component;

import com.beiding.dbrequest.server.ChannelHolder;
import com.beiding.dbrequest.server.RandomChannelSelector;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义的通道选择器
 * @author 丁常磊
 * @date 2021/9/22 10:45
 */

public class MyChannelSelector extends RandomChannelSelector {

    @Override
    public ChannelHandlerContext getOne(List<ChannelHolder> contexts) {
        List<ChannelHolder> channelHolders = new ArrayList<>(contexts);

        //按优先级排序
        channelHolders.sort((a, b) -> {
            Map<String, String> am = a.getMetadata();
            Map<String, String> bm = b.getMetadata();
            String ap = am.get("priority");
            String bp = bm.get("priority");
            double an = 0;
            double bn = 0;
            if (!StringUtil.isNullOrEmpty(ap)) {
                try {
                    an = Double.parseDouble(ap);
                } catch (Exception ignore) {
                }
            }

            if (!StringUtil.isNullOrEmpty(bp)) {
                try {
                    bn = Double.parseDouble(bp);
                } catch (Exception ignore) {
                }
            }
            if (an > bn) {
                return -1;
            } else if (an < bn) {
                return 1;
            }
            return 0;
        });

        if (channelHolders.size() == 0) {
            return null;
        }

        //最高优先级
        ChannelHolder first = channelHolders.get(0);
        String priority = first.getMetadata().get("priority");
        if (priority == null) {
            channelHolders.removeIf((z) -> z.getMetadata().get("priority") != null);
        }else{
            channelHolders.removeIf((z) -> !priority.equals(z.getMetadata().get("priority")));
        }

        //从最高优先级中选择一个
        return super.getOne(channelHolders);
    }
}
